<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ApiCollection;
use App\Http\Resources\ApiResource;
use App\Model\Repository\ApiRepository;
use App\Model\Repository\ApiRequestBodyRepository;
use App\Model\Repository\ApiResponseBodyRepository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class ApiController extends Controller
{

    public function index(Request $request)
    {
        $project_id = $request->get('project_id');
        return new ApiCollection(ApiRepository::when($project_id, function (Builder $query) use ($project_id) {
            $query->where('project_id', '=', $project_id);
        })->get());
    }

    /**
     * @param $id
     * @return array
     */
    public function show($id)
    {
        return [
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'api' => new ApiResource(ApiRepository::find($id)),
            ],
        ];
    }

    public function import(Request $request)
    {
        $content = $request->getContent();
        $content = json_decode($content, true);
        $name = $content['name'];
        $url = $content['url'];
        $remark = $content['remark'];
        $result = $content['result'];
        $params = $content['params'];
        $api = ApiRepository::where([
            ['api_name', '=', $name]
        ])->firstOrCreate([
            'api_name' => $name,
            'path' => $url,
            'remark' => $remark ?: '暂无',
            'domain' => '{{api}}',
            'method' => 'POST',
            'content_type' => 'x-www-form-urlencoded',
            'category_id' => 0,
            'project_id' => 1,
            'version' => '1.0',
        ]);
        ApiResponseBodyRepository::where([
            ['api_id', '=', $api->getApiId()]
        ])->firstOrCreate([
            'api_id' => $api->getApiId(),
            'body' => sprintf("```\n%s\n```", $result),
            'demo' => '暂无',
            'content_type' => 'JSON',
            'remark' => '暂无',
        ]);
        foreach ($params as $param) {
            if ($param['key'] == 'openid' || $param['key'] == 'device' || $param['key'] == 'loginToken') {
                continue;
            }
            ApiRequestBodyRepository::where([
                ['api_id', '=', $api->getApiId()],
                ['param_name', '=', $param['key']],
            ])->firstOrCreate([
                'api_id' => $api->getApiId(),
                'param_type' => 'int',
                'param_name' => $param['key'],
                'part' => 'body',
                'default' => '0',
                'remark' => $param['value'],
                'required' => 1,
            ]);
        }
        return [
            'code' => 200
        ];
    }
}
